package com.qf.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.pojo.User;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTUtils {


    private String key="lkdai";
    String issu = "qf-lkd";

    public String token(String user){
//        加密算法
        Algorithm algorithm = Algorithm.HMAC256(key);

//        计算过期时间
        long l = System.currentTimeMillis();

        l+=60*60*1000;

        Date date = new Date(l);

//        自定义头部
        HashMap hashMap = new HashMap<>();
        hashMap.put("alg","HS256");
        hashMap.put("typ", "jwt");

//        签发人

        String sign = JWT.create().withHeader(hashMap)
                .withSubject("token")
                .withIssuer(issu)
                .withClaim("body", user)
                .withIssuedAt(new Date())
                .withExpiresAt(date)
                .sign(algorithm);
        return sign;
    }


    public String verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(key);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(issu).build();

            DecodedJWT verify = verifier.verify(token);
            Claim body = verify.getClaim("body");
            String s = body.asString();
            return s;
        }catch (Exception e){
            return null;
        }
    }
}
